<template>
  <div class="edit-work">
    <div class="edit-work-container form-common">
      <h1 class="title-common">{{ isEdit ? '修改作品信息' : '新增作品' }}</h1>
      
      <div class="form-container">
        <form @submit.prevent="handleSubmit" class="edit-form">
          <div class="form-group">
            <label for="title">作品名称</label>
            <input 
              type="text" 
              id="title" 
              v-model="form.title" 
              required
              placeholder="请输入作品名称"
              class="form-control"
            >
          </div>

          <div class="form-group">
            <label for="writer">所属作家</label>
            <select 
              v-if="!writerId"
              id="writer" 
              v-model="form.writer_name" 
              required
              @change="handleWriterChange"
              class="form-control"
            >
              <option value="">请选择作家</option>
              <option 
                v-for="writer in writers" 
                :key="writer.id" 
                :value="writer.name"
              >
                {{ writer.name }}
              </option>
            </select>
            <div v-if="writerId && selectedWriterName" class="writer-info">
              <i class="fa fa-user"></i> 已选择作家：{{ selectedWriterName }}
            </div>
          </div>

          <div class="form-group">
            <label for="detail_link">详情链接</label>
            <input 
              type="url" 
              id="detail_link" 
              v-model="form.detail_link" 
              placeholder="请输入作品详情链接（如豆瓣）"
              class="form-control"
            >
          </div>

          <FileUpload
            label="封面图片"
            input-id="cover"
            :value="form.cover"
            :preview-url="coverPreview"
            @change="handleCoverChange"
          />

          <div class="form-group">
            <label class="checkbox-label">
              <input 
                type="radio" 
                name="workType"
                :value="0"
                v-model.number="form.is_biography"
              >
              该作者所写的作品
            </label>
          </div>

          <div class="form-group">
            <label class="checkbox-label">
              <input 
                type="radio" 
                name="workType"
                :value="1"
                v-model.number="form.is_biography"
              >
              与该作者相关的传记
            </label>
          </div>

          <div class="form-actions">
            <button type="submit" class="submit-btn">
              {{ isEdit ? '保存修改' : '添加作品' }}
            </button>
            <button type="button" class="cancel-btn" @click="goBack">取消</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 使用通用成功弹窗组件 -->
    <FormModal
      :show="showSuccess"
      title="添加成功"
      message="添加成功。"
      :countdown-seconds="countdownSeconds"
      @close="goToSourcePage"
      @confirm="goToSourcePage"
    />
  </div>
</template>

<script>
import FormModal from '@/components/FormModal.vue'
import FileUpload from '@/components/FileUpload.vue'

export default {
  name: 'EditWork',
  components: {
    FormModal,
    FileUpload
  },
  data() {
    return {
      form: {
        title: '',
        writer_name: '',
        writer_id: '',
        detail_link: '',
        cover: null,
        is_biography: false
      },
      coverPreview: null,
      writers: [],
      isEdit: false,
      writerId: null,
      selectedWriterName: '',
      showSuccess: false,
      countdownSeconds: 5,
      countdownTimer: null,
      sourcePage: null
    }
  },
  methods: {
    handleWriterChange() {
      const selectedWriter = this.writers.find(w => w.name === this.form.writer_name)
      if (selectedWriter) {
        this.form.writer_id = selectedWriter.id
      } else {
        this.form.writer_id = ''
      }
    },
    handleCoverChange(file) {
      this.form.cover = file
      if (file) {
        this.coverPreview = URL.createObjectURL(file)
      }
    },
    async handleSubmit() {
      try {
        // 验证作品类型选择
        if (this.form.is_biography === null || this.form.is_biography === undefined) {
          alert('请选择作品类型（作品或传记）')
          return
        }

        const formData = new FormData()
        formData.append('title', this.form.title)
        formData.append('writer_id', this.form.writer_id)
        formData.append('writer_name', this.form.writer_name)
        formData.append('detail_link', this.form.detail_link)
        formData.append('is_biography', this.form.is_biography ? '1' : '0')
        
        if (this.form.cover) {
          formData.append('cover', this.form.cover)
        }

        if (this.isEdit) {
          await this.$axios.put(`/api/works/${this.$route.params.id}`, formData)
        } else {
          await this.$axios.post('/api/works', formData)
        }

        // 显示成功弹窗
        this.showSuccess = true
        this.countdownSeconds = 5
        this.countdownTimer = setInterval(() => {
          this.countdownSeconds--
          if (this.countdownSeconds <= 0) {
            this.goToSourcePage()
          }
        }, 1000)
      } catch (error) {
        alert('保存失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    goBack() {
      this.$router.back()
    },
    goToSourcePage() {
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer)
        this.countdownTimer = null
      }
      
      if (this.sourcePage) {
        this.$router.push(decodeURIComponent(this.sourcePage))
      } else {
        this.$router.push('/works')
      }
    },
    async fetchWriters() {
      try {
        const response = await this.$axios.get('/api/writers', {
          params: { page: 1, pageSize: 1000 } // 获取所有作家
        })
        this.writers = response.data.writers || []
      } catch (error) {
        console.error('获取作家列表失败：', error)
      }
    },
    async fetchWork() {
      try {
        const response = await this.$axios.get(`/api/works/${this.$route.params.id}`)
        const work = response.data
        this.form.title = work.title
        this.form.writer_id = work.writer_id
        this.form.detail_link = work.detail_link || ''
        this.form.is_biography = work.is_biography
        
        // 获取作家名称
        if (work.writer_id) {
          const writerResponse = await this.$axios.get(`/api/writers/${work.writer_id}`)
          this.form.writer_name = writerResponse.data.name
        }
        
        // 设置封面预览
        if (work.cover_path) {
          this.coverPreview = `http://localhost:3000${work.cover_path}`
        }
      } catch (error) {
        console.error('获取作品信息失败：', error)
      }
    },
    async fetchWriterInfo() {
      try {
        const response = await this.$axios.get(`/api/writers/${this.writerId}`)
        const writer = response.data
        this.selectedWriterName = writer.name
        this.form.writer_name = writer.name
        this.form.writer_id = writer.id
      } catch (error) {
        console.error('获取作家信息失败：', error)
      }
    }
  },
  created() {
    // 记录来源页面
    if (this.$route.query.from) {
      this.sourcePage = this.$route.query.from
    } else if (this.$route.params.id) {
      this.sourcePage = `/works`
    } else {
      this.sourcePage = '/works'
    }
    
    this.writerId = this.$route.query.writerId || null
    this.selectedWriterName = this.$route.query.writerName || ''
    
    if (this.$route.params.id) {
      this.isEdit = true
      this.fetchWork()
    }
    
    if (!this.writerId) {
      this.fetchWriters()
    } else {
      // 如果有writerId，获取作家信息
      this.fetchWriterInfo()
    }
  },
  beforeDestroy() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer)
    }
  }
}
</script>

<style scoped>
@import '../assets/css/common.css';

.edit-work {
  padding: 2rem;
  background-color: #f4f7f6;
  min-height: 100vh;
}

.edit-work .title-common h1 {
  text-align: center;
  padding-bottom: 10px;
  border-bottom: #3F6580 solid 1px;
  color: #2c3e50;
  font-size: 24px;
  padding-bottom: 3rem !important;
  margin-bottom: 0 !important;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
}

.checkbox-label input[type="radio"] {
  margin: 0;
}

.writer-info {
  padding: 0.75rem;
  background-color: #e8f5e8;
  border: 1px solid #4caf50;
  border-radius: 4px;
  color: #2e7d32;
  font-weight: 500;
  margin-top: 0.5rem;
}

.writer-info i {
  margin-right: 0.5rem;
  color: #4caf50;
}
</style> 